package com.stockz.downloaderx.yahoo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.stockz.core.model.Bar;
import com.stockz.core.model.Scrip;
import com.stockz.downloaderx.AbstractSpanDownloader;

@Component
public class YahooDownloader extends AbstractSpanDownloader {

	@Autowired
	private YahooQuoteParser yahooQuoteParser;
	@Autowired
	@Qualifier("download.url.yahoo")
	private String downloadUrl = "http://finance.yahoo.com/d/quotes.csv";
	@Autowired
	@Qualifier("download.url.yahoo.param.symbol.key")
	private String paramKeySymbol = "s";
	@Autowired
	@Qualifier("download.url.yahoo.param.format.key")
	private String paramFormatKey = "f";
	@Autowired
	@Qualifier("download.url.yahoo.exchange.bse.suffix")
	private String bseSuffix = ".BO";
	
	@Override
	public String constructUri(Scrip scrip, Date start, Date end) {
		return downloadUrl+"?"+paramKeySymbol+"="+scrip.getCode()+bseSuffix+"&"+paramFormatKey+"="+yahooQuoteParser.getFormat();
	}
	
	@Override
	public int getOrder() {
		return 1;
	}

	@Override
	public String downloadRawData(String uri) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new URL(uri).openStream()));
			String line = null;
			String output = "";
			while((line = reader.readLine()) != null){
				output += "\n"+line;
			}
			return output;
		} catch (Exception e) {
			
		}finally{
			try {
				reader.close();
			} catch (IOException e) {
			}
		}
		return "";
	}

	@Override
	public List<Bar> parse(String text, Scrip scrip) {
		return yahooQuoteParser.parse(text, scrip);
	}
	
}
